require 'net/http'

#
# https://github.com/DennisOSRM/Project-OSRM/wiki/Server-api
# https://github.com/DennisOSRM/Project-OSRM/wiki/Output-json
#
class Osrm
    Host = "router.project-osrm.org"
    BasePath = "/viaroute?"

    def self.route_get(flat, flon, tlat, tlon)
        qstr = "loc=%s,%s&loc=%s,%s" % [flat, flon, tlat, tlon]
        path = BasePath + qstr
        Rails.logger.debug "Quering #{Host} for #{path}"
        Route.new Net::HTTP.get(Host, path)
        #Route.new open("tmp/route.json").read
    end

    class Route
        def initialize(answer)
            @a = JSON.parse(answer)
        end

        def coordinates
            ret = []
            Polylines::Decoder.decode_polyline(@a['route_geometry']).each{|lat,lon|
                ret << "%s,%s" % [lon/10,lat/10]
                Rails.logger.debug "pt@ " << ret.last.inspect
            }
            ret
        end

        def distance
            @a['route_summary']['total_distance']
        end

        def traveltime
            @a['route_summary']['total_time']
        end
    end
end
